/*******************************************************************************
 * @note Copyright (C) 2011-2022, Shanghai Panchip Microelectronics Co., Ltd. 
 * @SPDX-License-Identifier: Apache-2.0
 * @history - V0.1, 2022-09-28
*******************************************************************************/
#ifndef SERVICE_NET_H_
#define SERVICE_NET_H_

#include "ddl.h"
#include "timer3.h"
#include "userdef.h"
#include "flash.h"
#include "uart.h"
#include "pn_atcmd.h"
#include "stimer.h"
#include <stdbool.h>
#include "chirplan.h"

//#define NET_DEBUG
#ifdef NET_DEBUG
    #define net_debug pc_debug
#else 
    #define net_debug(format,...)
#endif

#define NET_EVT_NONE               0x00000000
#define NET_EVT_CHIRP_TX_DONE      0x00000001
#define NET_EVT_CHIRP_RX_DONE      0x00000002
#define NET_EVT_CHIRP_RX_TIMEOUT   0x00000004
#define NET_EVT_CHIRP_TX_TIMEOUT   0x00000008
#define NET_EVT_UART_TX_DONE       0x00000010
#define NET_EVT_UART_RX_DONE       0x00000020
#define NET_EVT_UART_TX_TIMEOUT    0x00000040
#define NET_EVT_UART_RX_TIMEOUT    0x00000080
#define NET_EVT_SETB_ACTIVE        0x00000100
#define NET_EVT_SETB_INACTIVE      0x00000200
#define NET_EVT_CAD_CHECK_TIMEOUT  0x00000400

#ifdef USBDONGLE
#define NET_EVT_SEND_18B20_TEMP    0x00000800
#endif

#define NET_BUF_SIZE 256

#define NET_SWITCH_STATE_IDLE  0  /* idle state */
#define NET_SWITCH_STATE_WACK  1  /* wait ack state */


enum net_status
{
    NET_STATUS_UNINITIALIZED = 0,
    NET_STATUS_INITIALIZED,
    NET_STATUS_CLI,
};

typedef enum net_status net_status_t;

typedef enum
{
    NET_STATE_INIT,
    NET_STATE_IDLE,
    NET_STATE_JOIN,
    NET_STATE_TX,
    NET_STATE_RX,
    NET_STATE_SLEEP
}net_state_t;

typedef struct net_msg
{
    int flag;       /* message flag */
    int len;        /* payload length */
    u8  buf[NET_BUF_SIZE];   /* payload */
}net_msg_t;

typedef struct
{
    net_status_t status;
    u32 count;
    u32 evt;
    net_state_t state;
    ctimer_t stimer_chirp_tx;  /* soft timer for chirp tx timeout */
    ctimer_t stimer_chirp_rx;  /* soft timer for chirp rx timeout */
    ctimer_t stimer_uart_rx;   /* soft timer for uart rx timeout */
	ctimer_t stimer_cad_chk;   /* soft timer for cad check */
#ifdef USBDONGLE
	ctimer_t stimer_18b20_send;
#endif
    net_msg_t uart_msg;
    net_msg_t rf_msg;
    int net_switch;
    bool rtc_on;
}net_proc_t;

extern chirp_app_data_t app_data;

void net_init(void);
void net_process(void);
void net_clean(void);
void net_get_config(chirp_t *config);
void net_io_set_evt(void);

#endif

